
<template>
  <!--关联商品-->
  <el-dialog
    title="关联商品"
    :visible="showModal"
    :modal-append-to-body="false"
    :append-to-body="true"
    width="65%"
    top="5vh"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <el-row>
      <el-form ref="queryData" :model="queryData" label-width="100px">
        <el-row type="flex" :gutter="20">
          <el-col :span="8">
            <el-form-item label="SPU编码" prop="spuNo">
              <el-input
                v-model="queryData.spuNo"
                placeholder="请输入SPU编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="SKU编码" prop="skuNo">
              <el-input
                v-model="queryData.skuNo"
                placeholder="请输入SKU编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品名称" prop="productName">
              <el-input
                v-model="queryData.productName"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="供应商编码"
              label-position="right"
              prop="supplyNo"
            >
              <el-input
                v-model="queryData.supplyNo"
                placeholder="请输入供应商编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="供应商名称"
              label-position="right"
              prop="supplyName"
            >
              <el-input
                v-model="queryData.supplyName"
                placeholder="请输入供应商名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="区域"
              label-position="right"
              prop="saleAreaName"
            >
              <el-input
                v-model="queryData.saleAreaName"
                placeholder="请输入区域"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="城市"
              label-position="right"
              prop="saleCityName"
            >
              <el-input
                v-model="queryData.saleCityName"
                placeholder="请输入城市"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="end">
          <el-button
              type="primary"
              @click="handleQueryData"
              >查询</el-button
            >
            <el-button
              @click="handleResetData('queryData')"
              >清空</el-button
            >
            <el-button
              v-if="tabsStatus === 'notAssociated'"
              type="primary"
              ghost
              @click="handleBatchAssociate"
              >批量关联</el-button
            >
            <el-button
              v-else
              ghost
              @click="handleBatchCancel"
              >批量取消</el-button
            >
        </el-row>
      </el-form>
    </el-row>
    <el-tabs
      v-model="tabsStatus"
      @tab-click="handleClickTabs"
      style="margin: 10px"
    >
      <el-tab-pane
        label="未关联"
        name="notAssociated"
      >
      </el-tab-pane>
      <el-tab-pane
        label="已关联"
        name="isAssociated"
      >
      </el-tab-pane>
    </el-tabs>
    <pl-table
      ref="multipleTable"
      border="border"
      use-virtual
      height="480"
      :data="dataSource"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
      @selection-change="handleCheckTableItem"
    >
      <pl-table-column fixed type="selection" width="50" />
      <pl-table-column
        v-for="column in columns"
        :key="column.key"
        :prop="column.key"
        :label="column.title"
        :property="column.key"
        :align="column.align"
        :min-width="120"
        :fixed="column.fixed"
        :show-overflow-tooltip="true"
        :type="column.type"
      >
        <template v-if="column.slot === 'action'" v-slot="scope">
          <el-button
            v-if="tabsStatus === 'notAssociated'"
            type="success"
            size="mini"
            @click="handleAssociateGoods(scope.row, scope.$index)"
            >关联</el-button
          >
          <el-button
            v-else
            size="mini"
            @click="handleCancelGoods(scope.row, scope.$index)"
            >取消</el-button
          >
        </template>
      </pl-table-column>
    </pl-table>
    <div class="pagination_wrap">
      <el-pagination
        background
        :total="totalPage"
        :current-page="nowPage"
        :page-size="pageShow"
        :page-sizes="pageSizeOpts"
        @current-change="handleChangePage"
        @size-change="handleChangePageSize"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
    <el-row slot="footer" style="text-align: center">
      <el-button type="primary" @click="handleCloseModal">返回表单</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapState, mapMutations } from 'vuex';
import { EDIT_MAINSUPPLY_MAX_LINKED_AMOUNT } from '@/constants/exportAmountLimit';
export default {
  props: {
    /* 表格表头 */
    columns: {
      type: Array,
      required: true
    },
    /* 请求查询数据接口区别未关联和已关联的入参 */
    distinctParams: {
      type: Object
    },
    /* 查询接口及类型 */
    requestApi: {
      type: Object,
      required: true
    },
    pageSizeOpts: {
      type: Array,
      default () {
        return [10, 100, 500, 1000];
      }
    },
    dimensionKeyList: { // 关联弹框维度key值列表 --- 以销售城市和sku为维度
      type: Array,
      default () {
        return ['saleCityUuid', 'skuNo']
      }
    }
  },
  data () {
    return {
      queryData: {
        spuNo: '', // spu编码
        skuNo: '', // sku编码
        productName: '', // 商品名称
        supplyNo: '', // 供应商编码
        supplyName: '', // 供应商名称
        saleAreaName: '', // 销售区域名称
        saleCityName: '', // 销售城市名称
      },
      dataSource: [], // 表格数据
      tabsStatus: 'notAssociated', // 当前tabs页签
      nowPage: 1, // 当前页
      pageShow: 10, // 每页条数
      totalPage: 0, // 总条数
      checkTableItemList: [], // 勾选的表格集合
    };
  },
  beforeDestroy () {
    this.DESTORY_STATE();
  },
  computed: {
    ...mapState('commonComps/batchMainSupplyAssociatedModal', [
      'associatedRowList', 'showModal'
    ])
  },
  methods: {
    ...mapMutations('commonComps/batchMainSupplyAssociatedModal', [
      'ASSOCIATED_GOODS', 'CANCEL_GOODS', 'CHANGE_MODAL_SWITCH', 'CLEAR_GOODS', 'DESTORY_STATE'
    ]),
    /* 获取map集合聚合后的已关联商品集合 */
    getAssociatedListFn () {
      let values = this.associatedRowList.values();
      let rowList = [];
      for (let item of values) {
        rowList.push(item);
      }
      return rowList;
    },
    /* 切换关联和未关联 */
    handleClickTabs () {
      this.nowPage = 1; // 每次切换tabs，都重置当前页为第一页
      this.handleQueryData();
    },
    // 查询条件全为空
    isAllEmptyByQueryData () {
      const emptyList = [];
      for (let key in this.queryData) {
        if (this.queryData[key]) {
          emptyList.push(false);
        } else {
          emptyList.push(true);
        }
      }
      return emptyList.every(item => item);
    },
    /* 查询方法 */
    handleQueryData () {
      if (
        this.isAllEmptyByQueryData() &&
        this.tabsStatus === 'notAssociated'
      ) {
        this.dataSource = [];
        this.totalPage = 0;
        return this.$message.warning('未关联查询至少输入一个检索条件')
      }
      if (this.getAssociatedListFn().length === 0 && this.tabsStatus === 'isAssociated') {
        this.dataSource = [];
        this.totalPage = 0;
        return false;
      }
      const {
        spuNo, // spu编码
        skuNo, // sku编码
        productName, // 商品名称
        supplyNo, // 供应商编码
        supplyName, // 供应商名称
        saleAreaName, // 销售区域名称
        saleCityName, // 销售城市名称
      } = this.queryData;
      const associatedUuids = this.getAssociatedListFn().map(item => {
        return item.uuid;
      });
      let otherParams = {};
      if (this.tabsStatus === 'notAssociated') {
        otherParams[this.distinctParams.notAssociated] = associatedUuids;
      }
      if (this.tabsStatus === 'isAssociated') {
        otherParams[this.distinctParams.associated] = associatedUuids;
      }
      const data = {
        spuNo, // spu编码
        skuNo, // sku编码
        productName, // 商品名称
        supplyNo, // 供应商编码
        supplyName, // 供应商名称
        saleAreaName, // 销售区域名称
        saleCityName, // 销售城市名称
        nowPage: this.nowPage,
        pageShow: this.pageShow,
        ...otherParams
      };
      this.getDataListAction(data);
    },
    /* 清空方法 */
    handleResetData (name) {
      this.$refs[name].resetFields();
    },
    /* 获取数据方法 */
    getDataListAction (data) {
      let { url, type } = this.requestApi;
      let requsetUrl = url[0];
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      let loading = this.$loading({ target: '.el-dialog__body' });
      ApiRequest(requsetUrl, type, data, false)
        .then((res) => {
          loading.close();
          if (res.retStatus === '1' && res.retData.results) {
            this.dataSource = res.retData.results;
            this.totalPage = res.retData.totalNum;
          } else {
            this.dataSource = [];
            this.totalPage = res.retData.totalNum;
          }
        })
        .catch(() => {
          loading.close();
        });
    },
    /* 批量关联方法 */
    handleBatchAssociate () {
      if (this.checkTableItemList.length === 0) {
        return this.$message.warning('请勾选商品');
      }
      this.checkTableItemList.forEach((value) => {
        this.ASSOCIATED_GOODS({ row: value, typeList: this.dimensionKeyList });
      });
      this.$nextTick(() => {
        this.handleQueryData();
      });
    },
    /* 批量取消方法 */
    handleBatchCancel () {
      if (this.checkTableItemList.length === 0) {
        return this.$message.warning('请勾选商品');
      }
      this.checkTableItemList.forEach((value) => {
        this.CANCEL_GOODS({ row: value, typeList: this.dimensionKeyList });
      });
      this.$nextTick(() => {
        this.handleQueryData();
      });
    },
    /* 关联方法 */
    handleAssociateGoods (row, index) {
      this.ASSOCIATED_GOODS({ row, typeList: this.dimensionKeyList });
      this.handleQueryData();
    },
    /* 取消方法 */
    handleCancelGoods (row, index) {
      this.CANCEL_GOODS({ row, typeList: this.dimensionKeyList });
      this.handleQueryData();
    },
    /* 表格数据勾选或勾选取消方法 */
    handleCheckTableItem (list) {
      this.checkTableItemList = list;
    },
    handleChangePage (page) {
      this.nowPage = page;
      this.handleQueryData();
    },
    handleChangePageSize (size) {
      this.nowPage = 1;
      this.pageShow = size;
      this.handleQueryData();
    },
    handleCloseModal () {
      if (this.associatedRowList.size > EDIT_MAINSUPPLY_MAX_LINKED_AMOUNT) {
        return this.$message.warning(
          `当前关联的最大行数不能超过${EDIT_MAINSUPPLY_MAX_LINKED_AMOUNT}`
        );
      }
      this.nowPage = 1;
      this.totalPage = 0;
      this.pageShow = 10;
      this.tabsStatus = 'notAssociated';
      this.dataSource = [];
      this.handleResetData('queryData');
      this.$emit('getRowList');
      this.CHANGE_MODAL_SWITCH(false);
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .el-dialog__body {
  padding: 10px 20px;
}
/deep/ .el-dialog__header {
  border-bottom: 1px solid #e8eaec;
}
/deep/ .el-dialog__footer {
  border-top: 1px solid #e8eaec;
}
/* 查询清空批量操作栏样式 */
.options_wrap {
  /deep/ .ivu-btn {
    margin-left: 15px;
  }
  /deep/ .ivu-btn-ghost {
    margin-right: 10px;
  }
}

/* 分页样式 */
.pagination_wrap {
  text-align: center;
  margin-top: 10px;
}
</style>
